import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_page/mine_business/mine_setting/bing_phone_page.dart';
import 'package:xvideos/hj_utils/api_service/mine_service.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/tools_base/global_store/store.dart';

import '../../../tools_base/event_bus/event_bus_util.dart';
import '../../../tools_base/event_bus/events.dart';

class BindPhoneLogic extends GetxController {
  late final phoneCtr = TextEditingController();
  late final codeCtr = TextEditingController();
  late final countDownNof = ValueNotifier(-1);
  Timer? _timer;
  late PhonePageType pageType;
  String title = '';
  String buttonTitle = '';

  @override
  void onInit() {
    super.onInit();
    pageType = Get.arguments ?? PhonePageType.bind;
    if (pageType == PhonePageType.bind) {
      title = '绑定手机';
      buttonTitle = '立即绑定';
    } else {
      title = '找回账号';
      buttonTitle = '立即找回';
    }
  }

  @override
  onClose() {
    super.onClose();
    _timer?.cancel();
  }

  onSendCode() async {
    if (_timer != null) return;
    if (phoneCtr.text.isEmpty || phoneCtr.text.length < 11) {
      showToast('请输入正确的手机号～');
      return;
    }
    final res = await MineService.postCaptchaCode(phoneCtr.text, pageType.type);
    if (res) {
      _timer?.cancel();
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        countDownNof.value += 1;
        if (countDownNof.value == 60) {
          _timer?.cancel();
          _timer = null;
          countDownNof.value = -1;
        }
      });
    }
  }

  onBindPhone() async {
    if (phoneCtr.text.isEmpty) {
      showToast('请输入正确的手机号～');
      return;
    }
    if (codeCtr.text.isEmpty) {
      showToast('请输入验证码～');
      return;
    }
    if (pageType == PhonePageType.bind) {
      final res = await MineService.bindPhone(phoneCtr.text, codeCtr.text);
      if (res) {
        showToast('绑定成功');
        globalStore.updateUserInfo();
        Get.back();
      }
    } else {
      final result = await globalStore.mobileLogin(phoneCtr.text, codeCtr.text);
      if (result != null) {
        showToast('登录成功');
        eventBus.emit(ReLoginEvent());
      }
    }
  }
}
